import { useEffect, useReducer } from "react";

type Options = {
  key1: string;
  key2: string;
  onAllPress: () => void;
};

type ReducerState = { key1: number; key2: number };
type ReducerAction = {
  type: "resetKey1" | "resetKey2" | "incrementKey1" | "incrementKey2";
};

const reducer = (state: ReducerState, action: ReducerAction): ReducerState => {
  switch (action.type) {
    case "incrementKey1":
      return { ...state, key1: state.key1 + 1 };
    case "incrementKey2":
      return { ...state, key2: state.key2 + 1 };
    case "resetKey1":
      return { ...state, key1: 0 };
    case "resetKey2":
      return { ...state, key2: 0 };
    default:
      throw new Error("Unknown action type");
  }
};

export default function useKeysPress({ key1, key2, onAllPress }: Options) {
  const [state, dispatch] = useReducer(reducer, { key1: 0, key2: 0 });

  const handleKeyDown = (e: KeyboardEvent) => {
    switch (e.key) {
      case key1:
        dispatch({ type: "incrementKey1" });
        break;
      case key2:
        dispatch({ type: "incrementKey2" });
        break;
    }
  };

  useEffect(() => {
    if (state.key1 === 1 && state.key2 === 1) {
      onAllPress();
    }
  }, [state.key1, state.key2]);

  const handleKeyUp = (e: KeyboardEvent) => {
    switch (e.key) {
      case key1:
        dispatch({ type: "resetKey1" });
        break;
      case key2:
        dispatch({ type: "resetKey2" });
        break;
    }
  };

  useEffect(() => {
    const abort = new AbortController();
    const opts = () => ({ signal: abort.signal });
    window.addEventListener("keydown", handleKeyDown, opts());
    window.addEventListener("keyup", handleKeyUp, opts());

    return () => {
      abort.abort();
    };
  }, []);

  return {};
}
